package com.hzw.saas.common.util;

import com.hzw.saas.common.util.orika.DateTime2DateConverter;
import com.hzw.saas.common.util.orika.DateTime2TimeConverter;
import ma.glasnost.orika.Converter;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MapperFactory;
import ma.glasnost.orika.converter.ConverterFactory;
import ma.glasnost.orika.impl.DefaultMapperFactory;

/**
 * orika的MapperFacade单例封装
 *
 * @author zzl
 * @since 04/26/2021
 */
public class MapperUtil {

    private static final MapperFactory mapperFactoryMapNoNulls;
    private static final MapperFactory mapperFactoryMapNulls;

    static {
        mapperFactoryMapNoNulls = new DefaultMapperFactory.Builder().mapNulls(false).build();
        mapperFactoryMapNulls = new DefaultMapperFactory.Builder().mapNulls(true).build();
        addCustomConverter();
    }

    private static void addCustomConverter() {
        registerConverter(new DateTime2DateConverter());
        registerConverter(new DateTime2TimeConverter());
    }

    /**
     * 注册转换器
     *
     * @param converter
     * @param <S>
     * @param <D>
     */
    public static <S, D> void registerConverter(Converter<S, D> converter) {
        ConverterFactory c1 = mapperFactoryMapNoNulls.getConverterFactory();
        c1.registerConverter(converter);
        ConverterFactory c2 = mapperFactoryMapNulls.getConverterFactory();
        c2.registerConverter(converter);
    }

    public static MapperFactory nfFactory() {
        return mapperFactoryMapNoNulls;
    }

    public static MapperFactory ntFactory() {
        return mapperFactoryMapNulls;
    }

    /**
     * map nulls = false
     * 不会映射原对象的null字段
     *
     * @return MapperFacade
     */
    public static MapperFacade nf() {
        return mapperFactoryMapNoNulls.getMapperFacade();
    }

    /**
     * map nulls = true
     * 会映射原对象的null字段
     *
     * @return MapperFacade
     */
    public static MapperFacade nt() {
        return mapperFactoryMapNulls.getMapperFacade();
    }

}
